package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.server.mapper.*;
import com.tanhua.server.pojo.*;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TestSoulService {

    @Autowired
    private QuestionUserLockMapper questionUserLockMapper;

    @Autowired
    private QuestionnaireMapper questionnaireMapper;

    @Autowired
    private SoulQuestionMapper soulQuestionMapper;

    @Autowired
    private SoulQuestionOptionMapper soulQuestionOptionMapper;

    @Autowired
    private QuestionnaireResultMapper questionnaireResultMapper;

    @Autowired
    private QuestionnaireReportMapper questionnaireReportMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 问卷列表
     * @return
     */
    public List<QuestionnaireVo> SQuestionnaireLike() {
        User user = UserThreadLocal.get();

        //查看用户锁住状态
        QueryWrapper<QuestionUserLock> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("user_id", user.getId());

        List<QuestionUserLock> questionUserLockList = this.questionUserLockMapper.selectList(wrapper1);
        //封装返回的List<QuestionnaireVo>
        List<QuestionnaireVo> questionnaireVoList = new ArrayList<>();

        //封装了前端需要的锁状态 和 问卷id
        for (QuestionUserLock userLock : questionUserLockList) {
            QuestionnaireVo questionnaireVo = new QuestionnaireVo();
            questionnaireVo.setIsLock(userLock.getIsLock());//封装锁状态
            questionnaireVo.setId(userLock.getQuestionnaireId() + "");//封装问卷id
            questionnaireVoList.add(questionnaireVo);
        }

        //封装问卷id
        List<Long> questionnaireIds = new ArrayList<>();
        for (QuestionUserLock questionUserLock : questionUserLockList) {
            questionnaireIds.add(questionUserLock.getQuestionnaireId());
        }

        for (Long questionnaireId : questionnaireIds) {
            System.out.println(questionnaireId);
        }

        QueryWrapper<Questionnaire> wrapper2 = new QueryWrapper<>();

        wrapper2.in("id", questionnaireIds);
        List<Questionnaire> questionnaires = this.questionnaireMapper.selectList(wrapper2);

        for (Questionnaire questionnaire : questionnaires) {
            for (QuestionnaireVo questionnaireVo : questionnaireVoList) {
                if (questionnaire.getId().toString().equals(questionnaireVo.getId())) {
                    questionnaireVo.setName(questionnaire.getName());//问卷名称
                    questionnaireVo.setCover(questionnaire.getCover());//封面
                    questionnaireVo.setLevel(questionnaire.getLevel().toString());//级别
                    questionnaireVo.setStar(questionnaire.getStar());//星别
                }
            }
        }

        //拿到试题数据
        QueryWrapper<SoulQuestion> wrapper3 = new QueryWrapper<>();
        wrapper3.in("questionnaire_id", questionnaireIds);
        List<SoulQuestion> soulQuestionList = this.soulQuestionMapper.selectList(wrapper3);

        //把问题vo填充到问卷vo中
        for (QuestionnaireVo questionnaireVo : questionnaireVoList) {
            List<SoulQuestionVo> soulQuestionsVoList = new ArrayList<>();
            //填充SoulQuestionVo的数据
            for (SoulQuestion soulQuestion : soulQuestionList) {
                if (questionnaireVo.getId().equals(soulQuestion.getQuestionnaireId().toString())) {
                    SoulQuestionVo soulQuestionsVo = new SoulQuestionVo();
                    soulQuestionsVo.setId(String.valueOf(soulQuestion.getId()));
                    soulQuestionsVo.setQuestion(soulQuestion.getStem());
                    //封装题目选项的数据
                    QueryWrapper<SoulQuestionOption> wrapper4 = new QueryWrapper<>();
                    wrapper4.eq("question_id", soulQuestion.getId());//TODO eq
                    List<SoulQuestionOption> soulQuestionOptions = this.soulQuestionOptionMapper.selectList(wrapper4);
                    List<SoulQuestionOptionVo> optionsVoList = new ArrayList<>();
                    for (SoulQuestionOption option : soulQuestionOptions) {
                        SoulQuestionOptionVo optionsVo = new SoulQuestionOptionVo();
                        optionsVo.setId(String.valueOf(option.getId()));
                        optionsVo.setOption(option.getContent());
                        optionsVoList.add(optionsVo);
                    }
                    soulQuestionsVo.setOptions(optionsVoList);//封装题目选项
                    soulQuestionsVoList.add(soulQuestionsVo);
                }
                //把问题对象填充到返回问卷vo对象
                questionnaireVo.setQuestions(soulQuestionsVoList);
            }
        }
        return questionnaireVoList;
    }

    /**
     * 测灵魂题目提交
     *
     * @param answersList
     */
    public String testSoul(List<Answers> answersList) {
        Integer score = 0;
        Long questionId = 0L;
        //计算得分
        for (Answers answers : answersList) {
            questionId = answers.getQuestionId();//题目id
            Long optionId = answers.getOptionId();//选项id

            QueryWrapper<SoulQuestionOption> wrapper = new QueryWrapper<>();
            wrapper.eq("question_id", questionId);
            wrapper.eq("id", optionId);
            SoulQuestionOption questionOption = this.soulQuestionOptionMapper.selectOne(wrapper);
            score += questionOption.getScore();//计算出成绩
        }

        System.out.println(score);
        //通过题目id查到对应的问卷id
        SoulQuestion soulQuestion = soulQuestionMapper.selectById(questionId);
        Long questionnaireId = soulQuestion.getQuestionnaireId();
        //默认初级开启

        if (questionnaireId <= 2) {
            QueryWrapper<QuestionUserLock> queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_id", UserThreadLocal.get().getId());
            queryWrapper.eq("questionnaire_id", questionnaireId + 1);
            QuestionUserLock questionUserLock = questionUserLockMapper.selectOne(queryWrapper);
            questionUserLock.setIsLock(0);
            questionUserLockMapper.update(questionUserLock, queryWrapper);
        }
        //根据问卷id,查看结果表，看总分在哪个区间，判断你的性格，并把数据都添加到报告表里
        QueryWrapper<QuestionnaireResult> query3 = new QueryWrapper<>();
        query3.eq("questionnaire_id", questionnaireId);
        List<QuestionnaireResult> questionnaireResults = questionnaireResultMapper.selectList(query3);

        QuestionnaireReport questionnaireReport = new QuestionnaireReport();
        questionnaireReport.setUserId(UserThreadLocal.get().getId());
        questionnaireReport.setQuestionnaireId(questionnaireId);
        for (QuestionnaireResult questionnaireResult : questionnaireResults) {
            String[] split = questionnaireResult.getScope().split(",");
            if (score >= Integer.valueOf(split[0]) && score <= Integer.valueOf(split[1])) {
                questionnaireReport.setResultId(questionnaireResult.getId());
                System.out.println("Result="+questionnaireResult.getId());
                break;
            }
        }
        questionnaireReportMapper.insert(questionnaireReport);
        return questionnaireReport.getId().toString();
    }





    /**
     * 灵魂测试结果
     * @param id
     * @return
     */
    public TestResultVo testResult(Long id) {
        TestResultVo soulResultVo = new TestResultVo();
        //报告
        QuestionnaireReport questionnaireReport = this.questionnaireReportMapper.selectById(id);
        //结果id
        Long resultId = questionnaireReport.getResultId();
        QuestionnaireResult questionnaireResult = this.questionnaireResultMapper.selectById(resultId);
        //封装结果描述
        soulResultVo.setConclusion(questionnaireResult.getContent());
        //鉴定图片
        soulResultVo.setCover(questionnaireResult.getCover());
        //封装性格维度
        List<Dimensions> dimensionsVoList = new ArrayList<>();

        dimensionsVoList.add(new Dimensions("提升", questionnaireResult.getExtroversion()));
        dimensionsVoList.add(new Dimensions("判断", questionnaireResult.getJudgement()));
        dimensionsVoList.add(new Dimensions("外向", questionnaireResult.getAbstraction()));
        dimensionsVoList.add(new Dimensions("理性", questionnaireResult.getRationality()));

        soulResultVo.setDimensions(dimensionsVoList);

        //通过resultId查询报告表，获取所有的用户，存到集合里
        QueryWrapper<QuestionnaireReport> wrapper = new QueryWrapper<>();
        wrapper.eq("result_id", resultId);
        List<QuestionnaireReport> questionnaireReports = this.questionnaireReportMapper.selectList(wrapper);
        List<Long> userIds = new ArrayList<>();
        for (QuestionnaireReport report : questionnaireReports) {
            userIds.add(report.getUserId());
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfos = this.userInfoMapper.selectList(queryWrapper);

        List<SimilarYou> similarYouVoList = new ArrayList<>();


        for (UserInfo userInfo : userInfos) {

            similarYouVoList.add(new SimilarYou(userInfo.getUserId(), userInfo.getLogo()));
        }
        soulResultVo.setSimilarYou(similarYouVoList);
        return soulResultVo;
    }

}
